package de.doegel.common.util;

import org.json.JSONObject;

import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;
import de.doegel.common.R;

public class GalleryImageDownloader extends ImageDownloader
{
	private String	jsonArgumentName;
	private String	videoUrlArgumentName;

	public GalleryImageDownloader( String jsonArgumentName , String videoUrlArgumentName )
	{
		this.jsonArgumentName = jsonArgumentName;
		this.videoUrlArgumentName = videoUrlArgumentName;
	}

	public void downloadForIndex( String url , ImageView view , int index )
	{
		super.download(url, ((ImageView) view));

	}

	protected void forceDownload( String url , ImageView imageView )
	{
		// State sanity: url is guaranteed to never be null in
		// DownloadedDrawable and cache keys.
		imageView.setTag(null);
		if (url == null || "".equals(url) || "".equals(url.trim()))
		{
			return;
		}

		if (cancelPotentialDownload(url, imageView))
		{
			GalleryBitmapDownloaderTask task = new GalleryBitmapDownloaderTask(imageView);
			imageView.setTag(task);
			task.execute(url);
		}
	}

	class GalleryBitmapDownloaderTask extends BitmapDownloaderTask
	{
		String	videoURL	= null;
		public GalleryBitmapDownloaderTask( ImageView imageView )
		{
			super(imageView);
		}

		@Override
		protected Bitmap doInBackground( String... params )
		{
			url = params[0];
			String urlToDownload = "";
			try
			{
				String content = AbstractHttpConnector.httpGET(url);
				JSONObject json = new JSONObject(content);
				// pfad
				urlToDownload = json.getString(jsonArgumentName);
				Log.i("doInBackground", "ImageUrl: " + urlToDownload);
				if (videoUrlArgumentName != null)
				{
					videoURL = json.getString(videoUrlArgumentName);
					
					Log.i("doInBackground", "videoURL: " + videoURL);
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			return downloadBitmap(urlToDownload);
		}

		protected void onPostExecute( Bitmap bitmap )
		{
			super.onPostExecute(bitmap);
			if (videoURL != null)
			{
				ImageView imageView = imageViewReference.get();
				if (imageView != null)
				{
					imageView.setTag(R.id.gallery_video_tag, videoURL);
				}
			}
		}
	}
}
